﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Security.Policy;
using IISLogAnalyzer.Common;
using IISLogAnalyzer.DbHelper;
using System.Data.SqlClient;
using System.Reflection;
using System.Collections;
using System.Collections.Concurrent;
using System.Threading;

namespace IISLogAnalyzer
{
    public partial class FormIISLogAnalyzer : Form
    {
        private string minDate = "";
        private string maxDate = "";

        DateTime dtTimeStart = DateTime.Now;
        DateTime dtTimeEnd = DateTime.Now;

        bool isInitialize = true;
        bool isInitializeWebSite = false;
        bool isInitializeDomain = false;

        public FormIISLogAnalyzer()
        {
            InitializeComponent();
        }

        #region 自定义方法

        #region 返回单个日志文件中的行数
        /// <summary>
        /// 返回单个日志文件中的行数
        /// </summary>
        /// <param name="filePath">单个IIS日志绝对路径</param>
        /// <returns></returns>
        static int CountLinesAsync(string filePath)
        {
            int count = 0;
            using (StreamReader file = new StreamReader(filePath))
            {
                string line;
                while ((line = file.ReadLine()) != null)
                {
                    count++;
                }
            }
            return count;
        }
        #endregion

        #region 分析并记录到数据库
        /// <summary>
        /// 分析并记录到数据库
        /// </summary>
        /// <param name="logFilePath">单个IIS日志绝对路径</param>
        public void AnalyzeLog(string logFilePath, CancellationToken token, System.Windows.Forms.ProgressBar progressBar = null, Label progressText = null)
        {
            Hashtable sqlHashtable = new Hashtable();

            string logTags = " "; // 日志空格
            Dictionary<string, string> logsTitles = new Dictionary<string, string>();
            logsTitles.Add("date", "_date*(\\d{4}-\\d{2}-\\d{2})");//日期：日志条目的日期。
            logsTitles.Add("time", "_time*(\\d{2}:\\d{2}:\\d{2})");//时间：日志条目的具体时间。
            logsTitles.Add("s-sitename", "_s_sitename*(\\S+)");//服务名称：IIS服务器的名称。
            logsTitles.Add("s-computername", "_s_computername*(\\S+)");//服务器名称：运行IIS的计算机的主机名。
            logsTitles.Add("s-ip", "_s_ip*(\\S+)");//服务器IP地址：运行IIS的计算机的IP地址。
            logsTitles.Add("cs-method", "_cs_method*(\\S+)");//方法：HTTP请求的方法，如GET、POST等。
            logsTitles.Add("cs-uri-stem", "_cs_uri_stem*(\\S+)");//URI资源：请求的完整URL路径（不包括查询字符串）。
            logsTitles.Add("cs-uri-query", "_cs_uri_query*(\\S+)");//URI查询：URL中的查询字符串部分。
            logsTitles.Add("s-port", "_s_port*(\\S+)");//服务器端口号：IIS服务器监听的端口号。
            logsTitles.Add("cs-username", "_cs_username*(\\S+)");//用户名：用于认证的用户名（如果有的话）。
            logsTitles.Add("c-ip", "_c_ip*(\\S+)");//客户端IP地址：发出请求的客户端的IP地址。
            logsTitles.Add("cs-version", "_cs_version*(\\S+)");//协议版本：使用的HTTP版本，如HTTP/1.1。
            logsTitles.Add("cs(User-Agent)", "_cs_user_agent*(\\S+)");//用户代理：发出请求的客户端的用户代理字符串，通常包含浏览器类型、版本和其他相关信息。
            logsTitles.Add("cs(Cookie)", "_cs_cookie*(\\S+)");//Cookie：发送到服务器的cookie（如果存在的话）。
            logsTitles.Add("cs(Referer)", "_cs_referer*(\\S+)");//引用网站：请求中包含的Referer头部，指示原始网页的URL（如果存在的话）。
            logsTitles.Add("cs-host", "_cs_host*(\\S+)");//主机：请求的主机名部分（有时与URI资源相同）。
            logsTitles.Add("sc-status", "_sc_status*(\\d+)");//协议状态：HTTP响应的状态码，如200、404等。
            logsTitles.Add("sc-substatus", "_sc_substatus*(\\d+)");//协议子状态：HTTP响应的子状态码（某些服务器可能会记录此字段）。
            logsTitles.Add("sc-win32-status", "_sc_win32_status*(\\d+)");//Win32状态：与Windows网络操作相关的状态码（非所有服务器都记录此字段）。
            logsTitles.Add("sc-bytes", "_sc_bytes*(\\d+)");//发送字节数：服务器发送给客户端的字节数。
            logsTitles.Add("cs-bytes", "_cs_bytes*(\\d+)");//接收字节数：客户端发送给服务器的字节数。
            logsTitles.Add("time-taken", "_time_taken*(\\d+)");//所用时间：完成此请求所需的总时间。
            Dictionary<int, string> logsValues = new Dictionary<int, string>();

            string pattern = "";

            var logData = new Dictionary<string, int>(); // 存储每个网站的访问和流量数据  
            string line;
            using (StreamReader file = new StreamReader(logFilePath))
            {
                int lineCount = CountLinesAsync(logFilePath);

                if (progressBar != null && progressText != null)
                {
                    ControlProxyHelper.SetValue(progressBar, "Minimum", 0);
                    ControlProxyHelper.SetValue(progressBar, "Maximum", 100);
                    ControlProxyHelper.SetValue(progressText, "Text", "0% - 0/" + lineCount);
                }

                int lineIdex = 0;

                while ((line = file.ReadLine()) != null)
                {
                    if (token.IsCancellationRequested)
                    {
                        break;
                    }

                    lineIdex++;

                    if (progressBar != null && progressText != null)
                    {
                        int gress = (int)((double)lineIdex / lineCount * 100);
                        ControlProxyHelper.SetValue(progressBar, "Value", gress);
                        if (gress % 10 == 0)
                        {
                            ControlProxyHelper.SetValue(progressText, "Text", gress + "% - " + lineIdex + "/" + lineCount);
                        }
                    }

                    if (line.StartsWith("#Fields:"))
                    {
                        logsValues = new Dictionary<int, string>();
                        string[] titles = line.Replace("#Fields:", "").Split(' ');
                        int i = 0;
                        foreach (string title in titles)
                        {
                            if (logsTitles.ContainsKey(title))
                            {
                                logsValues.Add(i, logsTitles[title].Split('*')[0]);
                                pattern += logsTitles[title].Split('*')[1] + logTags;
                                i++;
                            }
                        }
                    }

                    if (pattern.Length > 0)
                    {
                        if (pattern.EndsWith(logTags))
                        {
                            pattern = pattern.Substring(0, pattern.Length - 1);
                        }
                    }
                    else
                    {
                        continue;
                    }

                    // 使用正则表达式匹配日志行格式  
                    Match match = Regex.Match(line, @pattern);
                    if (match.Success)
                    {
                        if (TraverseDirectoryFiles.sqlHashtableQueue.Count >= TraverseDirectoryFiles.maxHascount)
                        {
                            Thread.Sleep(5000);//如何序列有100行没处理，就等待 5 秒。
                        }

                        try
                        {
                            PropertyInfo[] pros = new Model.iisloganalyzer().GetType().GetProperties();
                            List<SqlParameter> paras = new List<SqlParameter>();

                            string insertSql = "insert into dt_iis_logs_analyzer({columns}) values({values});";
                            string columns = "";
                            string values = "";
                            for (int i = 1; i < match.Groups.Count; i++)
                            {
                                columns += "[" + logsValues[i - 1] + "],";
                                values += "@" + logsValues[i - 1] + ",";//声明参数                            
                                paras.Add(new SqlParameter("@" + logsValues[i - 1] + "", match.Groups[i].Value));//对参数赋值
                            }

                            columns += "_add_time";
                            values += "@_add_time";//声明参数

                            paras.Add(new SqlParameter("@_add_time", DateTime.Now));//对参数赋值

                            sqlHashtable.Add(Utils.GenerateShortUniqueId() + "*" + insertSql.Replace("{columns}", columns).Replace("{values}", values), paras.ToArray());
                        }
                        catch (Exception e)
                        {
                            Logger.WriteLog("日志分析异常", e.Message + "：error：" + logFilePath);
                            break;
                        }

                        if (sqlHashtable.Count >= TraverseDirectoryFiles.maxSqlcount)
                        {
                            TraverseDirectoryFiles.sqlHashtableQueue.Enqueue(sqlHashtable);
                            TraverseDirectoryFiles.databaseProgressTotal++;
                            sqlHashtable = new Hashtable();
                        }
                    }
                }

                if (sqlHashtable.Count > 0)
                {
                    TraverseDirectoryFiles.sqlHashtableQueue.Enqueue(sqlHashtable);
                    TraverseDirectoryFiles.databaseProgressTotal++;
                    sqlHashtable = new Hashtable();
                }
            }
        }
        #endregion

        #region 绑定数据
        /// <summary>
        /// 绑定数据
        /// </summary>
        public void BindDate(string keys = "")
        {
            if (isInitialize) { return; }

            ControlProxyHelper.SetValue(dgvList, "DataSource", null);

            string sqlWhere = "[_date] between '" + dtpDateStart.Value.ToString("yyyy-MM-dd") + "' and '" + dtpDateEnd.Value.ToString("yyyy-MM-dd") + "'";

            if (int.Parse(ControlProxyHelper.GetValue(cbxServerName, "SelectedIndex").ToString()) > 0)
            {
                sqlWhere += " and [_s_computername] = '" + ControlProxyHelper.GetValue(cbxServerName, "Text").ToString() + "'";
            }

            if (int.Parse(ControlProxyHelper.GetValue(cbxWebSites, "SelectedIndex").ToString()) > 0)
            {
                sqlWhere += " and [_s_sitename] = '" + ControlProxyHelper.GetValue(cbxWebSites, "Text").ToString() + "'";
            }

            if (int.Parse(ControlProxyHelper.GetValue(cbxDomain, "SelectedIndex").ToString()) > 0)
            {
                sqlWhere += " and [_cs_host] = '" + ControlProxyHelper.GetValue(cbxDomain, "Text").ToString() + "'";
            }

            if (!string.IsNullOrEmpty(keys))
            {
                sqlWhere += " and ([_cs_host] = )'" + ControlProxyHelper.GetValue(cbxDomain, "Text").ToString() + "'";
            }

            double sd = Convert.ToDouble(SqlServerHelper.GetSingle(("SELECT Sum([_sc_bytes]) AS c FROM dt_iis_logs_analyzer where " + sqlWhere + "; ")));
            double ad = Convert.ToDouble(SqlServerHelper.GetSingle(("SELECT Sum([_cs_bytes]) AS c FROM dt_iis_logs_analyzer where " + sqlWhere + "; ")));

            ControlProxyHelper.SetValue(lbSend, "Text", Utils.GetByteUnite(sd));
            ControlProxyHelper.SetValue(lbAccepte, "Text", Utils.GetByteUnite(ad));

            string Ips = Convert.ToInt32(SqlServerHelper.GetSingle(("select count(1) from ( select distinct [_c_ip] as ip FROM dt_iis_logs_analyzer where +" + sqlWhere + ") as tab;"))).ToString();

            ControlProxyHelper.SetValue(lbIps, "Text", Ips);

            string strSql = "select ID," + Statics.GetSqlColumns() + " from dt_iis_logs_analyzer where " + sqlWhere + "";

            if (ControlProxyHelper.GetValue(ucPageManager1, "uc_search").ToString().Trim() != "")
            {
                strSql += " and " + Statics.GetLikeSqlColumns(ControlProxyHelper.GetValue(ucPageManager1, "uc_search").ToString().Trim());
            }

            int recordCount = Convert.ToInt32(SqlServerHelper.GetSingle(PagingHelper.CreateCountingSql(strSql)));

            ControlProxyHelper.SetValue(ucPageManager1, "uc_setPageDescription", recordCount);

            string orderby = "";

            if (int.Parse(ControlProxyHelper.GetValue(comboBox1, "SelectedIndex").ToString()) > 0)
            {
                if (int.Parse(ControlProxyHelper.GetValue(comboBox1, "SelectedIndex").ToString()) == 1)
                {
                    orderby = " [发送字节数]";
                }
                else
                {
                    orderby = " [发送字节数] desc";
                }
            }

            if (orderby == "")
            {
                if (int.Parse(ControlProxyHelper.GetValue(comboBox2, "SelectedIndex").ToString()) > 0)
                {
                    if (int.Parse(ControlProxyHelper.GetValue(comboBox2, "SelectedIndex").ToString()) == 1)
                    {
                        orderby = " [接收字节数]";
                    }
                    else
                    {
                        orderby = " [接收字节数] desc";
                    }
                }
            }
            else
            {
                if (int.Parse(ControlProxyHelper.GetValue(comboBox2, "SelectedIndex").ToString()) > 0)
                {
                    if (int.Parse(ControlProxyHelper.GetValue(comboBox2, "SelectedIndex").ToString()) == 1)
                    {
                        orderby += ",[接收字节数]";
                    }
                    else
                    {
                        orderby += ",[接收字节数] desc";
                    }
                }
            }

            if (orderby == "")
            {
                if (int.Parse(ControlProxyHelper.GetValue(comboBox3, "SelectedIndex").ToString()) > 0)
                {
                    if (int.Parse(ControlProxyHelper.GetValue(comboBox3, "SelectedIndex").ToString()) == 1)
                    {
                        orderby = "[耗时（ms）]";
                    }
                    else
                    {
                        orderby = "[耗时（ms）] desc";
                    }
                }
            }
            else
            {
                if (int.Parse(ControlProxyHelper.GetValue(comboBox3, "SelectedIndex").ToString()) > 0)
                {
                    if (int.Parse(ControlProxyHelper.GetValue(comboBox3, "SelectedIndex").ToString()) == 1)
                    {
                        orderby += ",[耗时（ms）]";
                    }
                    else
                    {
                        orderby += ",[耗时（ms）] desc";
                    }
                }
            }

            DataSet ds = SqlServerHelper.Query(PagingHelper.CreatePagingSql(recordCount, int.Parse(ControlProxyHelper.GetValue(ucPageManager1, "uc_pageSize").ToString()), int.Parse(ControlProxyHelper.GetValue(ucPageManager1, "uc_pageIndex").ToString()), strSql, (orderby == "" ? "id desc" : orderby + ",id desc")));

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                ds.Tables[0].Columns.Add("发送数量");

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    dr["发送数量"] = Utils.GetByteUnite(Convert.ToDouble(dr["发送字节数"].ToString()));
                }

                ds.Tables[0].Columns.Remove("发送字节数");

                ControlProxyHelper.SetValue(dgvList, "DataSource", ds.Tables[0]);
            }
        }
        #endregion

        #region 绑定网站
        /// <summary>
        /// 绑定网站
        /// </summary>
        public void BindWebSites()
        {
            if (ControlProxyHelper.GetValue(cbxServerName, "SelectedIndex").ToString() == "0")
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("index");
                dt.Columns.Add("title");

                DataRow dr = dt.NewRow();
                dr["index"] = "0";
                dr["title"] = "所有网站";

                dt.Rows.Add(dr);

                ControlProxyHelper.SetProperty(this, "cbxWebSites", "DisplayMember", "title");
                ControlProxyHelper.SetProperty(this, "cbxWebSites", "ValueMember", "index");
                ControlProxyHelper.SetProperty(this, "cbxWebSites", "DataSource", dt);
                ControlProxyHelper.SetProperty(this, "cbxWebSites", "SelectedIndex", 0);
                return;
            }

            DataSet ds = SqlServerHelper.Query("SELECT DISTINCT [_s_sitename] as title from dt_iis_logs_analyzer where _s_computername = '" + ControlProxyHelper.GetValue(cbxServerName, "Text").ToString() + "' order by _s_sitename;");

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("index");
                dt.Columns.Add("title");

                DataRow dr = dt.NewRow();
                dr["index"] = "0";
                dr["title"] = "所有网站";

                dt.Rows.Add(dr);

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    dr = dt.NewRow();
                    dr["index"] = (i + 1).ToString();
                    dr["title"] = ds.Tables[0].Rows[i]["title"].ToString();
                    dt.Rows.Add(dr);
                }

                ControlProxyHelper.SetProperty(this, "cbxWebSites", "DisplayMember", "title");
                ControlProxyHelper.SetProperty(this, "cbxWebSites", "ValueMember", "index");
                ControlProxyHelper.SetProperty(this, "cbxWebSites", "DataSource", dt);
                ControlProxyHelper.SetProperty(this, "cbxWebSites", "SelectedIndex", 0);
            }

        }
        #endregion

        #region 绑定网站域名
        /// <summary>
        /// 绑定网站域名
        /// </summary>
        public void BindDomain()
        {
            if (ControlProxyHelper.GetValue(cbxWebSites, "SelectedIndex").ToString() == "0")
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("index");
                dt.Columns.Add("title");

                DataRow dr = dt.NewRow();
                dr["index"] = "0";
                dr["title"] = "所有域名";

                dt.Rows.Add(dr);

                ControlProxyHelper.SetProperty(this, "cbxDomain", "DisplayMember", "title");
                ControlProxyHelper.SetProperty(this, "cbxDomain", "ValueMember", "index");
                ControlProxyHelper.SetProperty(this, "cbxDomain", "DataSource", dt);
                ControlProxyHelper.SetProperty(this, "cbxDomain", "SelectedIndex", 0);
                return;
            }

            DataSet ds = SqlServerHelper.Query("SELECT DISTINCT [_cs_host] as title from dt_iis_logs_analyzer where _s_sitename = '" + ControlProxyHelper.GetValue(cbxWebSites, "Text").ToString() + "' order by _cs_host ; ");

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("index");
                dt.Columns.Add("title");

                DataRow dr = dt.NewRow();
                dr["index"] = "0";
                dr["title"] = "所有域名";

                dt.Rows.Add(dr);

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    dr = dt.NewRow();
                    dr["index"] = (i + 1).ToString();
                    dr["title"] = ds.Tables[0].Rows[i]["title"].ToString();
                    dt.Rows.Add(dr);
                }

                ControlProxyHelper.SetProperty(this, "cbxDomain", "DisplayMember", "title");
                ControlProxyHelper.SetProperty(this, "cbxDomain", "ValueMember", "index");
                ControlProxyHelper.SetProperty(this, "cbxDomain", "DataSource", dt);
                ControlProxyHelper.SetProperty(this, "cbxDomain", "SelectedIndex", 0);
            }

        }
        #endregion

        #region 绑定数据库中最大最小日期与数据量
        /// <summary>
        /// 绑定数据库中最大最小日期与数据量
        /// </summary>
        public void BindDataBaseTotalMinMax()
        {
            DataSet ds = ds = SqlServerHelper.Query("SELECT max([_date]) as endDate,min([_date]) as startDate,count(1) counts  from dt_iis_logs_analyzer;");
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0]["startDate"].ToString() != "" && ds.Tables[0].Rows[0]["endDate"].ToString() != "")
                {
                    minDate = Utils.ObjectToDateTime(ds.Tables[0].Rows[0]["startDate"]).ToString("yyyy-MM-dd");
                    maxDate = Utils.ObjectToDateTime(ds.Tables[0].Rows[0]["endDate"]).ToString("yyyy-MM-dd");
                    ControlProxyHelper.SetStatusStripText(statusStrip1, 0, "日志生成区间：【" + Utils.ObjectToDateTime(ds.Tables[0].Rows[0]["startDate"]).ToString("yyyy-MM-dd") + "】~【" + Utils.ObjectToDateTime(ds.Tables[0].Rows[0]["endDate"]).ToString("yyyy-MM-dd") + "】；记录数：【" + ds.Tables[0].Rows[0]["counts"] + "】");
                    ControlProxyHelper.SetValue(dtpDateStart, "Text", minDate);
                    ControlProxyHelper.SetValue(dtpDateEnd, "Text", maxDate);
                }
            }
        }
        #endregion

        #region 绑定服务器
        /// <summary>
        /// 绑定服务器
        /// </summary>
        public void BindServer()
        {
            DataSet ds = SqlServerHelper.Query("SELECT DISTINCT [_s_computername] as title,[_s_ip] as ip from dt_iis_logs_analyzer order by _s_computername;");

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("ip");
                dt.Columns.Add("title");

                DataRow dr = dt.NewRow();
                dr["ip"] = "0";
                dr["title"] = "所有服务器";

                dt.Rows.Add(dr);

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    dr = dt.NewRow();
                    dr["ip"] = ds.Tables[0].Rows[i]["ip"].ToString();
                    dr["title"] = ds.Tables[0].Rows[i]["title"].ToString();
                    dt.Rows.Add(dr);
                }

                ControlProxyHelper.SetProperty(this, "cbxServerName", "DisplayMember", "title");
                ControlProxyHelper.SetProperty(this, "cbxServerName", "ValueMember", "ip");
                ControlProxyHelper.SetProperty(this, "cbxServerName", "DataSource", dt);
                ControlProxyHelper.SetProperty(this, "cbxServerName", "SelectedIndex", 0);
            }
        }
        #endregion

        #endregion

        #region 窗体控件事件

        /// <summary>
        /// 打开存放IIS日志的目录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAnalyzer_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
            {
                folderBrowserDialog.Description = "请选择一个存放IIS日志的目录";
                folderBrowserDialog.RootFolder = Environment.SpecialFolder.MyComputer; // 设置起始文件夹  

                // 显示文件夹选择对话框  
                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    // 用户选择了文件夹  
                    string selectedFolder = folderBrowserDialog.SelectedPath;

                    TraverseDirectoryFiles.sqlHashtableQueue = new ConcurrentQueue<Hashtable>();
                    TraverseDirectoryFiles.filePaths = new List<string>();
                    TraverseDirectoryFiles.filePathsCountIindex = 0;
                    TraverseDirectoryFiles.databaseProgress = 0;
                    TraverseDirectoryFiles.databaseProgressTotal = 0;

                    TraverseDirectoryFiles.TraverseDirectory(selectedFolder);

                    List<string> files = TraverseDirectoryFiles.filePaths;

                    if (files.Count == 0)
                    {
                        MessageBox.Show("当前目录没有找到IIS日志！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        FormProgress formProgress = new FormProgress(this);
                        formProgress.ShowDialog();
                        BindServer();
                    }
                }
            }
        }

        /// <summary>
        /// 设置显示列
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnColums_Click(object sender, EventArgs e)
        {
            FormSetColumns fsc = new FormSetColumns();
            fsc.ShowDialog();
            ControlProxyHelper.SetValue(ucPageManager1, "uc_pageIndex", 1);
            BindDate();
        }

        /// <summary>
        /// 列表绑定事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvList_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            foreach (DataGridViewColumn dgvc in dgvList.Columns)
            {
                dgvc.SortMode = DataGridViewColumnSortMode.NotSortable;

                if (dgvc.HeaderText == "URI资源")
                {
                    dgvc.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                }
                else
                {
                    dgvc.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                }
            }
        }

        private void dtpDateStart_ValueChanged(object sender, EventArgs e)
        {
            if (Utils.ObjectToDateTime(dtpDateStart.Text) < Utils.ObjectToDateTime(minDate))
            {
                dtpDateStart.Text = minDate;
            }
            ControlProxyHelper.SetValue(ucPageManager1, "uc_pageIndex", 1);
            BindDate();
        }

        private void dtpDateEnd_ValueChanged(object sender, EventArgs e)
        {
            if (Utils.ObjectToDateTime(dtpDateEnd.Text) > Utils.ObjectToDateTime(maxDate))
            {
                dtpDateEnd.Text = maxDate;
            }
            ControlProxyHelper.SetValue(ucPageManager1, "uc_pageIndex", 1);
            BindDate();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ControlProxyHelper.SetValue(ucPageManager1, "uc_pageIndex", 1);
            BindDate();
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            ControlProxyHelper.SetValue(ucPageManager1, "uc_pageIndex", 1);
            BindDate();
        }

        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            ControlProxyHelper.SetValue(ucPageManager1, "uc_pageIndex", 1);
            BindDate();
        }

        private void btnChart_Click(object sender, EventArgs e)
        {
            if (minDate == "" || maxDate == "")
            {
                MessageBox.Show("没有数据可分析！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            FormCharts formCharts = new FormCharts(maxDate, minDate);
            formCharts.ShowDialog();
        }

        private void cbxWebSites_SelectedIndexChanged(object sender, EventArgs e)
        {
            ControlProxyHelper.SetValue(ucPageManager1, "uc_pageIndex", 1);
            if (!isInitializeWebSite)
            {
                isInitializeDomain = true;
                BindDomain();
                BindDate();
                isInitializeDomain = false;
            }
        }

        private void cbxServerName_SelectedIndexChanged(object sender, EventArgs e)
        {
            ControlProxyHelper.SetValue(ucPageManager1, "uc_pageIndex", 1);
            isInitializeWebSite = true;
            BindWebSites();
            isInitializeDomain = true;
            BindDomain();
            isInitializeDomain = false;
            BindDate();
            isInitializeWebSite = false;
        }

        private void cbxDomain_SelectedIndexChanged(object sender, EventArgs e)
        {
            ControlProxyHelper.SetValue(ucPageManager1, "uc_pageIndex", 1);
            if (!isInitializeDomain)
            {
                BindDate();
            }
        }

        private void FormIISLogAnalyzer_Load(object sender, EventArgs e)
        {
            BindDataBaseTotalMinMax();

            comboBox1.SelectedIndex = 0;
            comboBox2.SelectedIndex = 0;
            comboBox3.SelectedIndex = 0;

            BindServer();

            isInitialize = false;
            BindDate();
        }

        #endregion


    }
}
